package org.example.simple;

import com.rabbitmq.client.*;
import org.example.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.建立连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        //2.建立连接
        Connection connection =connectionFactory.newConnection();
        //3.创建信道
        Channel channel = connection.createChannel();
        //4.声明队列，如果生产者声明队列的时候，消费者就不应声明队列了
        /**
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * queue:从那个队列进行消费消息
         * autoAck:自动确认还是手动确认
         * callback：消费消息的时候触发的逻辑是
         */
        channel.queueDeclare("hello",true,false,false,null);
        //5.消费消息

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            //这里类似于回调函数，实际上根据业务需求，来写具体的方法和逻辑
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息");
            }
        };
        channel.basicConsume("hello",true,consumer);
        //再有多个消费者
        Thread.sleep(2000);
//        channel.close();
//        connection.close();
    }
}
